<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
use app\index\model\UserModel;

class Index extends Controller
{
	protected function _initialize() {
		$type=get_brower_type();
		$this->assign('browder_type',$type);
	}	
	public function map(){
		$this->assign("lng",input("lng"));
		$this->assign("lat",input("lat"));
		$this->assign("name",input("name"));
		return $this->fetch();
	}	
	//鼓励金判断
	private function do_pay($goods,$agent,&$p_score,&$zs_score,&$pay_price,$user_id,$nums){
		if($pay_price<1){
			return;
		}
		if($agent['is_score']==1){//开启鼓励金营销
			$p_score=number_format($goods['dk_price'],4) * $nums;//抵扣积分
			$user=db('info_user')->field("score")->find($user_id);
		    if($p_score&&$user['score']>=$p_score){//用户积分抵扣
				$pay_price=$pay_price-$p_score;//抵扣后订单价格
			}else{//赠送鼓励金
				$p_score=0;
				$zs_score=number_format($goods['zs_price'],4) * $nums;//赠送积分
				if($agent['score']<$zs_score){
					header("Content-type: text/html; charset=utf-8"); 
					echo '商家鼓励金不足！！！';exit;
				}
			}			
		}
	}	
	//添加收银订单
	private function add_syorder($goods_id,$sn,$agent_id,$pay_type,$p_score,$zs_score,
	$price,$pay_price,$user_id,$status,$type,$message=""){
				$data['sn']=$sn;
				$data['goods_id']=$goods_id;
				$data['agent_id']=$agent_id;
				$data['user_id']=$user_id;
				$data['total_price']=$price;
				$data['pay_type']=$pay_type;
				$data['pay_price']=$pay_price;
				$data['add_time']=now_time();
				$data['need_score']=$p_score;
				$data['give_score']=$zs_score;
				$data['status']=$status;
				$data['type']=$type;
				$data['message']=$message;
				$res=db('agent_syorder')->insertGetId($data);
				return $res;				
	}
	//下单
	public function topay(){
		$user_id=session('info_user')['id'];
		$goods_id=input("goods_id");	//商品id
		$nums=input('nums');			//商品数量
		$content =  input('content');	//用户留言
		
		$cut_url = "http://".$_SERVER['HTTP_HOST']."/index/index/order_pay_code?good_id=$goods_id&nums=$nums&user_id=$user_id&content=$content";
		$order_pay_url='http://www.vshop88.net/code/code.php?url='.urlencode($cut_url).'&margin=1&size=10';
		$this->assign('cut_url',$cut_url);
		return  $this->fetch();
	}
	
	//订单二维码
	function order_pay_code(){
		
		$goods_id 	= input('good_id');
		$nums 		= input('nums');
		$user_id 	= input('user_id');
		$content 	= input('content');
		
		$goods=db("agent_goods")->field("agent_id,dk_price,zs_price,oem_id,sale_price")->find($goods_id);
		$agent=db('info_agent')->find($goods['agent_id']);
		
		$type=get_brower_type();//判断是微信还是支付宝打开
		if($type==1){
			$pay_type=3;
		}else{
			$pay_type=2;
		}
		$p_score=0;//抵扣鼓励金
		$zs_score=0;//赠送鼓励金
		$price=$goods['sale_price']*$nums;//订单价
		$pay_price=$price;//实际支付价格
		$this->do_pay($goods,$agent,$p_score,$zs_score,$pay_price,$user_id,$nums);
		$sn=order_create_no();
		Db::startTrans();
		$res=$this->add_syorder($goods_id,$sn,$agent["id"],$pay_type,$p_score,$zs_score,$price,$pay_price,$user_id,1,4,input('content'));
		if(!$res){
			Db::rollback();
			echo '下单失败';exit;
		}
		$log_res=add_log($nums,$goods_id,$user_id,$agent['id'],0,'',$sn,$pay_type,1,$price,$pay_price,1);
		
		if(!$log_res){
			Db::rollback();
			echo '下单失败';exit;
		}
		Db::commit();
		if($pay_price==0){//纯积分
			header("Content-type: text/html; charset=utf-8"); 
			echo '支付成功';exit;
		}
		if($type==1){//支付宝
	        if($agent['is_state']==1){
        		$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,1,$sn,'');
				Header("Location: $url");
				exit;
        	}else{
        		header("Content-type: text/html; charset=utf-8"); 
        		echo '支付失败';exit;
        	}
		}elseif ( $type==2 ) {//微信扫码
				if($agent['is_state']==1){
        			$url=pay_code($agent['cb_no'],$agent['cb_miyao'],$agent['cb_clerk'],$pay_price,2,$sn,'');
					Header("Location: $url");
					exit;
	        	}else{
					header("Content-type: text/html; charset=utf-8"); 
	        		echo '支付失败';exit;
	        	}
		} 
	}
	
	
	//订单付款	
	public function pay(){
		$goods_id=input("goods_id");
		if (!session('info_user')) {
			session('redirect_url','index/index/pay?goods_id='.$goods_id);
			$this->redirect('index/index/login',array('to'=>'p'));
        }
		$goods=db("agent_goods")->find($goods_id);
		$agent=db("info_agent")->field("agent_name")->find($goods['agent_id']);
		$this->assign('goods',$goods);
		$this->assign('agent',$agent);
		return  $this->fetch();
	}	
	public function goodsshow(){
		$goods=db("agent_goods")->find(input("goods_id"));
		$goods['content'] = html_entity_decode($goods['content']);
		$comments=db('goods_comment')->where('goods_id',input("goods_id"))->limit(3)->select();
		if($comments){
			foreach($comments as $c=>$v){
				$imgs=$v['img_url'];
				if($imgs){
					$imgs=explode(",", $imgs);
					$comments[$c]['imgs']=$imgs;
				}
			}
		}
		$this->assign('comments',$comments);
		$this->assign('goods',$goods);
		return  $this->fetch();
	}	
	 //登陆
    public function index()
    {
    	return  $this->fetch();
    }
	//首页商家
	public function get_agents(){
		$longitude = input('longitude');
		$latitude = input('latitude');
		$order = ' order by juli asc ';
		$where =" where status = 1 and is_state = 1 and is_huilu = 1 and  id!=1 and oem_id = ".config('cut_oem_id');
		$field='a.action,a.is_score,ad_score,a.start_time,a.end_time,a.id,a.agent_name,a.add_time,a.logo,a.address,a.longitude,a.latitude,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$latitude.'*PI()/180-latitude*PI()/180)/2),2)+COS('.$latitude.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$longitude.'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli';
		$sql = 'select '.$field.' from info_agent as a '.$where.$order;
		$resultList=Db::query($sql);
		return json(["list"=>$resultList]);
	}
    //登陆
    public function login()
    {
    	if(request()->isPost()){
    		$type=get_brower_type();
    		$param=input('post.');
    		$where['mobile'] 	= $param['phone'];
    		$where['password'] 	= md5_salt($param['pwd']);
    		$where['oem_id'] 	= config('cut_oem_id');
    		$user_info = db('info_user')->where($where)->find();
    		if($user_info){
    			if($user_info['status'] == 1){
    				//检查openid
			   		if(input('openid') && strlen(input('openid')) >2){
			   			$filed = 'openid';
			   			$key_id = input('openid');
			   		}else if(input('alipay_id') && strlen(input('alipay_id')) >2){
			   			$filed = 'alipay_id';
			   			$key_id = input('alipay_id');
			   		}
			   		
			   		if($type ==1 || $type ==2){
			   			//检查openid是否存在
				   		$is_user = Db::table('info_user')->where($filed, $key_id)->find();
				   		if(!$is_user){
				   			//更新用户信息
					   		$resut = Db::table('info_user')->where('id', $user_info['id'])->update([$filed => $key_id]);
				   			if($resut){
								session('info_user',$user_info);
								$this->success('登录成功','index/member/index');
				   			}else{
				   				$this->error('登录失败402');
				   			}
				   		}else{
				   			session('info_user',$user_info);
							$this->success('登录成功','index/member/index');
				   		}
			   		}else{
			   			
			   			if($user_info){
							session('info_user',$user_info);
							$this->success('登录成功','index/member/index');
			   			}else{
			   				$this->error('登录失败402');
			   			}
			   		}
			   		
			   		
    			}else{
    				$this->error('账号异常，已冻结!');
    			}
    		}else{
    			$this->error('用户名密码错误');
    		}
    	}else{
    		$type=get_brower_type();//判断是微信还是支付宝打开
	    	$redirect='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	    	if($type==1){
				$auth_code=input("auth_code");
				$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
			}else if($type==2){
				$auth_code=input("code");
				$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
			}else{
				$this->assign('to',input("to"));
				return $this->fetch('login2');
			}
			if(!$auth_code){
				Header("Location: $url");
				exit;
			}else{
				if($type==1){//支付宝openid
					$pay_type = 3;
					$field="alipay_id";
					$openid=user_ali_id($auth_code);
				}elseif($type==2){//微信openid
					$pay_type = 2;
					$field="openid";
					if(session('cut_auth_code') != $auth_code && session('prior_auth_code') != $auth_code){
						session('prior_auth_code',session('cut_auth_code'));
						session('cut_auth_code',$auth_code);
						$openid=user_wx_id($auth_code);
					}else{
						Header("Location: $url");
						exit;
					}
				}
				$openid_info['key_type'] = $pay_type;
				$openid_info['key_id'] = $openid;
				$this->assign('openid_info',$openid_info);
			}
    	}
		$this->assign('to',input("to"));
       return  $this->fetch();
    }
    
    
   	//注册
    public function regist()
    {
    	if(request()->isPost()){
    		$result = check_sendcode($_POST['mobile'], $_POST['yzm'], '发送成功');
			if($result != 1) {
				$this->error('验证码错误或过期');
			}
			//检查openid
	   		if(input('openid') && strlen(input('openid')) >2){
	   			$ch_where['openid'] = input('openid');
	   		}else{
	   			$ch_where['alipay_id'] = input('alipay_id');
	   		}
			$ch_where['mobile'] = $_POST['mobile'];
    		$user_info = db('info_user')->where($ch_where)->find();
    		//检查手机号码
	    	if($user_info){
	    		$this->error('该手机号码已经注册');
	   		}
	   		//检查openid
	   		if(input('openid') && strlen(input('openid')) >2){
	   			$filed = 'openid';
	   			$key_id = input('openid');
	   			//查找用户信息
	   			$open_user = db('info_user')->where('openid',input('openid'))->find();
	   		}else if(input('alipay_id') && strlen(input('alipay_id')) >2){
	   			$filed = 'alipay_id';
	   			$key_id = input('alipay_id');
	   			//查找用户信息
	   			$open_user = db('info_user')->where('alipay_id',input('alipay_id'))->find();
	   		}
	   		
	   		if($open_user){
	   			$pwd = md5_salt($_POST['pwd']);
	   			//更新用户信息
	   			$resut = Db::table('info_user')->where('id', $open_user['id'])->update(['password' => $pwd,'mobile'=>$_POST['mobile']]);
	   			if($resut){
					session('info_user',$open_user);
					$this->success('登录成功','index/member/index');
	   			}else{
	   				$this->error('注册失败402');
	   			}
	   			
	   		}else{
	   			if(!$user_info){
    				$city_user_info = db('info_user')->where('mobile',$_POST['mobile'])->find();
	   				if($city_user_info){
	   					//更新用户信息
			   			$resut = Db::table('info_user')->where('id', $city_user_info['id'])->update([$filed => $key_id]);
			   			if($resut){
							session('info_user',$city_user_info);
							$this->success('登录成功','index/member/index');
			   			}else{
			   				$this->error('注册失败403');
			   			}
	   				}
	   			}
	   			if($_POST['fromuid'] && $_POST['fromuid']>0){
	   				//获取上级信息
					$up_user_info = db('info_user')->where('id',$_POST['fromuid'])->find();
	   			}else{
	   				//获取默认用户信息
	   				$up_user_info = db('info_user')->where('id',1)->find();
	   			}
	   			$_POST['agency_id1'] 	= $up_user_info['agency_id1'];
				$_POST['agency_id2'] 	= $up_user_info['agency_id2'];
				$_POST['tj_pt'] 		= $up_user_info['tj_pt'];
				$_POST['tj_agent'] 		= $up_user_info['tj_agent'];
				$_POST['level'] 		= $up_user_info['id'];
				$_POST['password'] 		= md5_salt($_POST['pwd']);
				$_POST['oem_id'] 		= config('cut_oem_id');
				$_POST['add_time']		= now_time();
				$user_model = new UserModel();
				$rest=$user_model->allowField(true)->save($_POST);
				if($rest){
					$user_id = db('info_user')->getLastInsID();
					$user_info = db('info_user')->where('id',$user_id)->find();
					session('info_user',$user_info);
					$this->success('注册成功','index/member/index');
				}
				$this->error('注册失败');
	   		}
    	}else{
    		$type=get_brower_type();//判断是微信还是支付宝打开
	    	$redirect='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	    	if($type==1){
				$auth_code=input("auth_code");
				$url ='https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id='.config('alipay_appid').'&scope=auth_base&redirect_uri='.urlencode($redirect);
			}else{
				$auth_code=input("code");
				$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect';
			}
			if(!$auth_code){
				Header("Location: $url");
				exit;
			}else{
				if($type==1){//支付宝openid
					$pay_type = 3;
					$field="alipay_id";
					$openid=user_ali_id($auth_code);
				}elseif($type==2){//微信openid
					$pay_type = 2;
					$field="openid";
					if(session('cut_auth_code') != $auth_code && session('prior_auth_code') != $auth_code){
						session('prior_auth_code',session('cut_auth_code'));
						session('cut_auth_code',$auth_code);
						$openid=user_wx_id($auth_code);
					}else{
						Header("Location: $url");
						exit;
					}
				}
				$openid_info['key_type'] = $pay_type;
				$openid_info['key_id'] = $openid;
				$this->assign('openid_info',$openid_info);
			}
    	}
       return  $this->fetch();
    }
    
    
    //修改密码
    public function return_pwd()
    {
    	if(request()->isPost()){
    		
    		$result = check_sendcode($_POST['mobile'], $_POST['yzm'], '发送成功');

			if($result != 1) {
				$this->error('验证码错误或过期');
			}
    		$user_info = db('info_user')
    					->where('mobile',$_POST['mobile'])
    					->where('oem_id',config('cut_oem_id'))
    					->find();
	    	if($user_info){
	    			$pwd = md5_salt($_POST['pwd']);
	    			$result = Db::table('info_user')->where('id', $user_info['id'])->update(['password' => $pwd]);
	    			if($result){
	    				$this->success('修改成功','index/member/login');
	    			}else{
	    				$this->error('修改失败');
	    			}
	   		}else{
	   			$this->error('用户不存在');
	   		}
    	}
    	
       return  $this->fetch();
    }
    
    /**
     * 获取验证码
     * 注意防盗刷
     * 
     */
    function verify_code(){
    	
    	if(request()->isPost()){
    		return get_code($_POST['mobile'],1);
    	}
    }
    
    
    //绑定手机号
    function my_mobile(){
    	//查找当前oem
    	$oem_info = db('info_oem')->where('id',config('cut_oem_id'))->find();
    	$this->assign('oem_info',$oem_info);
    	
    	if(request()->isPost()){
    		$result = check_sendcode($_POST['mobile'], $_POST['verifycode'], '发送成功');

			if($result != 1) {
				$this->error('验证码错误或过期');
			}
    		$user_info = db('info_user')
    						->where('mobile',$_POST['mobile'])
    						->find();
	    	if($user_info){
	    		$this->error('该手机号码已经注册');
	   		}
	   		$password = md5_salt($_POST['password']);
	   		$info_user = session('info_user');
    		$reult = Db::table('info_user')->where('id', $info_user['id'])->update(['mobile' => $_POST['mobile'],'password'=>$password]);
    		if($reult){
    			$this->success('绑定成功');
    		}else{
    			$this->error('绑定失败');
    		}
    	}
    	return  $this->fetch();
    }
    
    /**
     * 退出登录
     */
    public function logout() {
        session(null);
        $this->success('退出成功', 'index/index');
    } 
    //shop_info
    public function shop_info()
    {
    	$data = db('info_agent')->where('id',input('agent_id'))->find();
		$data['longitude']=$data['longitude']?$data['longitude']:'113.013481';
		$data['latitude']=$data['latitude']?$data['latitude']:'25.773369';
		$ads=db('agent_advertisement')->where('agent_id',input('agent_id'))->select();
		$wh['agent_id']=input('agent_id');
		$wh['goods_state']=2;
		$wh['is_recommend']=2;
		$goods=db("agent_goods")->where($wh)->limit(5)->select();
		$this->assign('goods',$goods);
    	$this->assign('data',$data);
		$this->assign('ads',$ads);
        return  $this->fetch();
    }
	
	//云商铺APP下载界面
	public function down(){
		return  $this->fetch();
	}
}
